package com.quanzhi.openapi.config;

import com.mongodb.client.MongoClient;
import com.mongodb.client.MongoClients;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.mongodb.core.MongoTemplate;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;

@Configuration
public class MongoConfig {

    @Value("${spring.data.mongodb.host}")
    private String mongoHost;

    @Value("${spring.data.mongodb.port}")
    private String mongoPort;

    @Value("${spring.data.mongodb.database}")
    private String mongoDatabase;

    @Value("${spring.data.mongodb.username}")
    private String mongoUsername;

    @Value("${spring.data.mongodb.password}")
    private String mongoPassword;

    @Bean
    public MongoClient mongoClient() {
        String encodedUsername = encode(mongoUsername);
        String encodedPassword = encode(mongoPassword);
        String uri = "mongodb://" + encodedUsername + ":" + encodedPassword + "@" + mongoHost + ":" + mongoPort + "/" + mongoDatabase;
        return MongoClients.create(uri);
    }

    @Bean
    public MongoTemplate mongoTemplate() {
        return new MongoTemplate(mongoClient(), mongoDatabase);
    }

    private String encode(String value) {
        try {
            return URLEncoder.encode(value, StandardCharsets.UTF_8.toString())
                    .replace("+", "%20") // URLEncoder encodes spaces as '+', replace with '%20'
                    .replace("*", "%2A") // Handle other reserved characters if needed
                    .replace("%7E", "~"); // Handle '~' if needed
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("Failed to encode MongoDB credentials", e);
        }
    }
}
